package cn.kgc.chlm.dao.impl;

import cn.kgc.chlm.dao.UserDao;
import cn.kgc.chlm.entity.User;
import cn.kgc.chlm.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    @Override
    public List<User> selectUserAll() {
        return null;
    }

    @Override
    public User login(User user) {
        List<User> users = null;
        User loginUser = null;

        try {
            conn = JdbcUtil.getConnection();
            String loginSql = "select * from `user` where username = ? and password = ?";
            pstmt = conn.prepareStatement(loginSql);
            pstmt.setString(1,user.getUsername());
            pstmt.setString(2,user.getPassword());
            rs = pstmt.executeQuery();
            users = new ArrayList<>();
            while (rs.next()){
                loginUser = new User();
                loginUser.setId(rs.getInt("id"));
                loginUser.setName(rs.getString("name"));
                loginUser.setUsername(rs.getString("username"));
                loginUser.setMobilePhone(rs.getString("mobile_phone"));
                loginUser.setCash(rs.getDouble("cash"));
                users.add(loginUser);

            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (users.size() < 1){
            return null;
        }else {
            return users.get(0);
        }
    }

    @Override
    public User selectUserById(Integer id) {
        return null;
    }

    @Override
    public int addUser(User user) {
        return 0;
    }

    @Override
    public int updateUser(User user) {
        int n = 0;
        try {
            //通过工具类创建连接
            conn = JdbcUtil.getConnection();
            System.out.println("userDao:"+conn);
            //修改我们用户支付后的钱数
            String updataUserSql = "update `user` set cash = ? where id = ?";
            pstmt = conn.prepareStatement(updataUserSql);
            pstmt.setDouble(1,user.getCash());
            pstmt.setInt(2,user.getId());
            n = pstmt.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return n;
    }

    @Override
    public int deleteUser(User user) {
        return 0;
    }
}
